extends Node2D


var claw;
var gear;
@export var claw_length = 150;
@export var claw_radius = 20;
@export var claw_angle = 0;

func _ready():
	gear = get_parent()
	claw = get_child(0);
	rotate_claw(0, false);
	claw.resize(claw_radius, false)
	
	gear.gear_speed = 300

func _draw():
	var to = Vector2(claw_length, 0).rotated(deg_to_rad(claw_angle));
	draw_line(Vector2(0, 0), to, gear.self_c, 3);
	draw_circle(to, 3, gear.self_c);

func _process(delta):
	var _self = self;
	var mp = _self.get_local_mouse_position();
	
	#rotate_claw(45)
	#gear.position = Vector2(500, 400)
	
	if(mp.distance_to(Vector2.ZERO) < _self.gear.gear_radius):
		var fct = gb.numKey_factor();
		if(gb.kp(KEY_L)):
			rotate_claw(10 * delta * fct)
		if(gb.kp(KEY_J)):
			rotate_claw(-10 * delta * fct)
		if(gb.kp(KEY_I)):
			extend_claw(10 * delta * fct)
		if(gb.kp(KEY_K)):
			extend_claw(-10 * delta * fct)

func rotate_claw(x, is_relative = true):
	if(is_relative):	claw_angle += x;
	else: claw_angle = x;
	claw.position = Vector2.RIGHT.rotated(deg_to_rad(claw_angle)) * claw_length;
	if(claw.catched_obj and claw.catched_obj.grab_obj):
		claw.catched_obj.grab_obj.rotate_claw(x, is_relative)
	queue_redraw()

func extend_claw(x, is_relative = true):
	var gd = preload("res://scripts/gear/collision.gd");
	if(is_relative):	claw_length += x;
	else: claw_length = x;
	claw.position = Vector2.RIGHT.rotated(deg_to_rad(claw_angle)) * claw_length;
	if(claw.catched_obj):
		var cgear = claw.catched_obj;
		var min_dis = gd.get_min_geardis(self.gear, claw.catched_obj) + 5
		if(claw_length < min_dis):
			extend_claw(min_dis, false);
	queue_redraw()
	

func get_speed():
	gear.gear_speed = 300
	return 300;# self.get_parent().gear_speed
